<?php
defined('BASEPATH') or exit('No direct script access allowed!');

class Task extends CI_Controller {
  function __construct() {
    parent::__construct();
    session_start();
    header('Content-Type: application/json');
    if(empty($_SESSION['login'])) {
      response('{status:"error",data:"Unauthorized"}', 401);
    }
    $this->load->model('MTask', 'mtask');
  }

  /* /api/project/(:any)/task/(:any)     goes here */
  function index($projHash, $taskHash) {
    switch($_SERVER['REQUEST_METHOD'])
    {
      case 'GET':
      case 'get':
        $this->get($projHash, $taskHash);
        break;
      case 'POST':
      case 'post':
        $this->post($projHash, $taskHash);
        break;
      case 'PATCH':
      case 'patch':
        $this->patch($projHash, $taskHash);
        break;
      case 'DELETE':
      case 'delete':
        $this->delete($projHash, $taskHash);
        break;
      default:
        response('{status:"error",data:"Method not support!"}', 405);
    }
  }

  public function showAll($projectHash) {
    echo json_encode($this->mtask->getAll($projectHash));
  }

  private function get($projHash, $taskHash) {
    echo json_encode($this->mtask->get($taskHash));
  }

  private function post($projHash, $taskHash) {
    if(!isset($_POST['name'], $_POST['tagColor'], $_SESSION['user']->name, $_POST['detail'])) {
      response('{status:"error",data:"Invalid request field!"}', 406);
    }
    echo json_encode($this->mtask->add($projHash, $taskHash, $_POST['name'], $_POST['tagColor'], $_SESSION['user']->name, $_POST['detail']));
  }

  private function patch($projHash, $taskHash) {
    parse_str(file_get_contents('php://input'), $_PATCH);
    $old = $this->mtask->get($taskHash);
    $this->mtask->update($taskHash, array(
      'hide' => false,
      'finished' => empty($_PATCH['finished']) ? $old->finished : !!$_PATCH['finished'],
      'name' => empty($_PATCH['name']) ? $old->name : $_PATCH['name'],
      'tagColor' => empty($_PATCH['tagColor']) ? $old->tagColor : $_PATCH['tagColor'],
      'detail' => empty($_PATCH['detail']) ? $old->detail : $_PATCH['detail']
    ));
    $this->get($projHash, $taskHash);
  }

  private function delete($projHash, $taskHash) {
    $this->mtask->delete($projHash, $taskHash);
    echo '{status:"done", data:"request complete."}';
  }
}
